package com.umeox.watch.moto.contact.ui;


import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.CallLog;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.tencent.mmkv.MMKV;
import com.umeox.moto.common.log.Logger;
import com.umeox.moto.common.utils.NetUtils;
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity;
import com.umeox.moto.watch.themes.util.UToast;
import com.umeox.moto.watch.themes.widget.TextView;
import com.umeox.watch.moto.agora.InternalConstants;
import com.umeox.watch.moto.contact.R;
import com.umeox.watch.moto.contact.adapter.CallLogAdapter;
import com.umeox.watch.moto.contact.model.MergeCallLog;
import com.umeox.watch.moto.contact.utils.Utils;
import com.umeox.watch.moto.dataservice.DataProvider;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;


public class CallLogListActivity extends ThemeAppCompatActivity implements CallLogAdapter.OnItemClickListener {
    private static final long UNTIL_TIME = TimeUnit.MINUTES.toMillis(5);
    private RecyclerView mCallLogRv;
    private AsyncQueryHandler callLogAsyncQueryHandler;//异步查询数据库类对象

    private String[] mProjections;

    private List<MergeCallLog> mCallLogs;
    private CallLogAdapter mCallLogAdapter;

    private TextView mEmptyTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_call_log);
        mCallLogRv = findViewById(R.id.call_log_rv);
        mEmptyTv = findViewById(R.id.tv_contact_empty);
        callLogAsyncQueryHandler = new CallLogAsyncQueryHandler(getContentResolver());
        mProjections = new String[]{
                CallLog.Calls.CACHED_NAME,  //姓名
                CallLog.Calls.NUMBER,    //号码
                CallLog.Calls.TYPE,  //呼入/呼出(2)/未接
                CallLog.Calls.DATE,  //拨打时间
                CallLog.Calls.DURATION,   //通话时长
        };
        mCallLogAdapter = new CallLogAdapter(this, this);
        mCallLogRv.setLayoutManager(new LinearLayoutManager(this));
        mCallLogRv.setAdapter(mCallLogAdapter);
        callLogAsyncQueryHandler.startQuery(0, null, CallLog.Calls.CONTENT_URI, mProjections, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);
    }

    @Override
    public void onItemClick(int position,String phoneNumber) {
        Log.e("TAG","=========onItemClick=======");
        phoneCall(phoneNumber);
    }

    private void phoneCall(String phoneNumber) {
        if(TextUtils.isEmpty(phoneNumber)){
            return;
        }
        if (PhoneNumberUtils.isEmergencyNumber(phoneNumber)) {
            Intent intent = new Intent("android.intent.action.CALL_PRIVILEGED", Uri.parse("tel:" + phoneNumber));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else {
            if (!NetUtils.hasSimCard()) {
                UToast.showCustomToast(CallLogListActivity.this, getString(R.string.no_simcard_str), Toast.LENGTH_LONG);
                return;
            }

            if (!Utils.isPhoneIdle(mContext)) {
                Logger.i("电话功能正在使用");
                Utils.endCall(mContext);
                return;
            }
            Intent intent = new Intent("android.intent.action.CALL_PRIVILEGED", Uri.parse("tel:" + phoneNumber));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }

    private void voiceCall(String friendId) {
        if (!Utils.isPhoneIdle(mContext)) {
            return;
        }

        if (!NetUtils.isNetworkAvailable()) {
            UToast.showCustomToast(mContext, getString(R.string.sim_state_unknown), Toast.LENGTH_LONG);
            return;
        }
        Uri uri = Uri.parse(InternalConstants.OUTGOING_VOICE_CALL + "?" + InternalConstants.CALL_QUERY_PARA_FOLLOWER_ID + "=" + friendId);
        Intent intent = new Intent(InternalConstants.ACTION_OUTGOING_VIDEO_CALL, uri);
        startActivity(intent);
    }

    private void videoCall(String friendId) {
        if (!Utils.isPhoneIdle(mContext)) {
            return;
        }
        if (!NetUtils.isNetworkAvailable()) {
            UToast.showCustomToast(mContext, getString(R.string.sim_state_unknown), Toast.LENGTH_LONG);
            return;
        }
        if (DataProvider.isVideoCallForbidden()) {
            UToast.showCustomToast(mContext, getString(R.string.video_call_forbid_str), Toast.LENGTH_LONG);
        } else {
            final long lastVideoCallTimeMillis = MMKV.defaultMMKV().getLong(friendId, -UNTIL_TIME);
            final long videoCallEnableTime = lastVideoCallTimeMillis + UNTIL_TIME - SystemClock.elapsedRealtime();
            if (videoCallEnableTime > 0) {

                final int minutes = (int) Math.max(1, TimeUnit.MILLISECONDS.toMinutes(videoCallEnableTime));
                int resId = R.string.video_call_countdown;
                UToast.showCustomToast(mContext, getString(resId, minutes), Toast.LENGTH_LONG);
                return;
            }

            Uri uri = Uri.parse(InternalConstants.OUTGOING_VIDEO_CALL + "?" + InternalConstants.CALL_QUERY_PARA_FOLLOWER_ID + "=" + friendId);
            Intent intent = new Intent(InternalConstants.ACTION_OUTGOING_VIDEO_CALL, uri);
            startActivity(intent);
        }
    }

    @Override
    public void onRefreshEmptyView(boolean empty) {

    }


    private class CallLogAsyncQueryHandler extends AsyncQueryHandler {
        public CallLogAsyncQueryHandler(ContentResolver cr) {
            super(cr);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            super.onQueryComplete(token, cookie, cursor);
            Logger.e("****************onQueryComplete*********************");
            Logger.e("cursor.getCount() = " + cursor.getCount());
            mCallLogs = new ArrayList<>();
            try {
                if (cursor.getCount() > 0) {
                    cursor.moveToFirst(); // 游标移动到第一项
                    for (int i = 0; i < cursor.getCount(); i++) {
                        cursor.moveToPosition(i);
                        String name = cursor.getString(0);
                        String number = cursor.getString(1);
                        int type = cursor.getInt(2);
                        long date = cursor.getLong(3);
                        int duration = cursor.getInt(4);
                        if (TextUtils.isEmpty(name)) {
                            name = Utils.getContactNameFromPhoneBook(CallLogListActivity.this, number);
                        }
                        // 创建联系人对象
                        MergeCallLog callLog = new MergeCallLog();
                        callLog.setPhoneNumber(number);
                        callLog.setName(TextUtils.isEmpty(name) ? number : name);
                        callLog.setAvatarUrl(DataProvider.getContactPhoto(number));
                        callLog.setTime(date);
                        callLog.setType(MergeCallLog.CALL_TYPE);
                        if (type == CallLog.Calls.INCOMING_TYPE) {
                            callLog.setCallType(MergeCallLog.INCOMING_TYPE);
                        } else if (type == CallLog.Calls.OUTGOING_TYPE) {
                            callLog.setCallType(MergeCallLog.OUTGOING_TYPE);
                        } else if (type == CallLog.Calls.MISSED_TYPE) {
                            callLog.setCallType(MergeCallLog.MISSED_TYPE);
                        }
                        mCallLogs.add(callLog);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cursor.close();
//                getVOIPCallLogs();
//                sortCallLog();
                //查询自己数据库的全部通话记录
                if (!mCallLogs.isEmpty()) {
                    mCallLogAdapter.getDatas().addAll(mCallLogs);
                    mCallLogAdapter.notifyDataSetChanged();
                    mEmptyTv.setVisibility(View.GONE);
                } else {
                    mEmptyTv.setVisibility(View.VISIBLE);
                }

            }
            super.onQueryComplete(token, cookie, cursor);
        }
    }

    private void sortCallLog() {
        Collections.sort(mCallLogs, (o1, o2) -> (int) (o2.getTime() - o1.getTime()));
        if (mCallLogs.size() > 10) {
            mCallLogs = mCallLogs.subList(0, 10);
        }
    }

   /* private void getVOIPCallLogs() {
        List<ContentValues> contentValues = Utils.getVideoCallLogs(this);
        if (contentValues != null) {
            Logger.e("contentValues.size=" + contentValues.size());
            for (ContentValues callLog : contentValues) {
                String friendId = (String) callLog.get(DataProvider.VideoCallProvider.FRIEND_ID);
                long startTime = (long) callLog.get(DataProvider.VideoCallProvider.START_TIME);
                long endTime = (long) callLog.get(DataProvider.VideoCallProvider.END_TIME);
                int callType = (int) callLog.get(DataProvider.VideoCallProvider.CALL_TYPE);
                long duration = (long) callLog.get(DataProvider.VideoCallProvider.CALL_DURATION);
                int newCall = (int) callLog.get(DataProvider.VideoCallProvider.NEW_CALL);
                MergeCallLog mergeCallLog = new MergeCallLog();
                if (callType == InternalConstants.CallType.INCOMING_CALL.getType() ||
                        callType == InternalConstants.CallType.OUTGOING_CALL.getType() ||
                        callType == InternalConstants.CallType.CALL_MISSED_TYPE.getType()) {
                    mergeCallLog.setPhoneNumber(friendId);
                    String name = Utils.getContactNameFromPhoneBook(CallLogListActivity.this, friendId);
                    mergeCallLog.setName(TextUtils.isEmpty(name) ? friendId : name);
                    mergeCallLog.setAvatarUrl(DataProvider.getContactPhotoUrl(friendId));
                } else {
                    mergeCallLog.setFriendId(friendId);
                    ContentValues contentValues1 = DataProvider.getContactByFriendId(friendId);
                    if (contentValues1 != null) {
                        mergeCallLog.setName(contentValues1.getAsString(DataProvider.ContactProvider.NICKNAME));
                        mergeCallLog.setAvatarUrl(contentValues1.getAsString(DataProvider.ContactProvider.PHOTO_URL));
                    }
                }

                mergeCallLog.setTime(startTime);

                if (callType == InternalConstants.CallType.INCOMING_VIDEO_CALL.getType()) {
                    mergeCallLog.setType(MergeCallLog.VIDEO_CALL_TYPE);
                    mergeCallLog.setCallType(MergeCallLog.INCOMING_TYPE);
                } else if (callType == InternalConstants.CallType.OUTGOING_VIDEO_CALL.getType()) {
                    mergeCallLog.setType(MergeCallLog.VIDEO_CALL_TYPE);
                    mergeCallLog.setCallType(MergeCallLog.OUTGOING_TYPE);
                } else if (callType == InternalConstants.CallType.INCOMING_VOIP_CALL.getType()) {
                    mergeCallLog.setType(MergeCallLog.VOICE_CALL_TYPE);
                    mergeCallLog.setCallType(MergeCallLog.INCOMING_TYPE);
                } else if (callType == InternalConstants.CallType.OUTGOING_VOIP_CALL.getType()) {
                    mergeCallLog.setType(MergeCallLog.VOICE_CALL_TYPE);
                    mergeCallLog.setCallType(MergeCallLog.OUTGOING_TYPE);
                } else if (callType == InternalConstants.CallType.VIDEO_MISSED_TYPE.getType()) {
                    mergeCallLog.setType(MergeCallLog.VIDEO_CALL_TYPE);
                    mergeCallLog.setCallType(MergeCallLog.MISSED_TYPE);
                } else if (callType == InternalConstants.CallType.VOIP_MISSED_TYPE.getType()) {
                    mergeCallLog.setType(MergeCallLog.VOICE_CALL_TYPE);
                    mergeCallLog.setCallType(MergeCallLog.MISSED_TYPE);
                } else if(callType == InternalConstants.CallType.INCOMING_CALL.getType()){
                    mergeCallLog.setType(MergeCallLog.CALL_TYPE);
                    mergeCallLog.setCallType(MergeCallLog.INCOMING_TYPE);
                } else if(callType == InternalConstants.CallType.OUTGOING_CALL.getType()){
                    mergeCallLog.setType(MergeCallLog.CALL_TYPE);
                    mergeCallLog.setCallType(MergeCallLog.OUTGOING_TYPE);
                } else if(callType == InternalConstants.CallType.CALL_MISSED_TYPE.getType()){
                    mergeCallLog.setType(MergeCallLog.CALL_TYPE);
                    mergeCallLog.setCallType(MergeCallLog.MISSED_TYPE);
                }
                mCallLogs.add(mergeCallLog);
            }

        }
    }*/

}
